﻿using Grow.Module.Service;
using Grow.Module.Thread;
using Grow.WebAPI.CreateWebAPI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;

namespace Grow.WebAPI.MiniAPI.CreateWebAPI
{
    public class WebAPIBuilder : IWebAPIBuilder
    {
        private readonly string _group;
        private readonly IEndpointRouteBuilder _endpointRouteBuilder;

        public WebAPIBuilder(string group, IEndpointRouteBuilder endpointRouteBuilder)
        {
            _group = group;
            _endpointRouteBuilder = endpointRouteBuilder;
        }

        public IWebAPIBuilder Map<TRequest, TResponse>(MapTypeEnum mapType, string route, Func<TRequest, IServiceContext, ICancellationTokenContext, TResponse> actionFunc, string summary = "")
        {
            RouteHandlerBuilder routeHandlerBuilder = mapType switch
            {
                MapTypeEnum.Get => _endpointRouteBuilder.MapGet(route, actionFunc),
                MapTypeEnum.Post => _endpointRouteBuilder.MapPost(route, actionFunc),
                MapTypeEnum.Put => _endpointRouteBuilder.MapPut(route, actionFunc),
                MapTypeEnum.Patch => _endpointRouteBuilder.MapPut(route, actionFunc),
                MapTypeEnum.Delete => _endpointRouteBuilder.MapDelete(route, actionFunc),
                _ => _endpointRouteBuilder.MapGet(route, actionFunc),
            };
            _ = routeHandlerBuilder
               .WithTags(_group)
               .WithSummary(summary)
               .WithOpenApi();
            return this;
        }


        public IWebAPIBuilder Map<TResponse>(MapTypeEnum mapType, string route, Func<IServiceContext, ICancellationTokenContext, TResponse> actionFunc, string summary = "")
        {
            RouteHandlerBuilder routeHandlerBuilder = mapType switch
            {
                MapTypeEnum.Get => _endpointRouteBuilder.MapGet(route, actionFunc),
                MapTypeEnum.Post => _endpointRouteBuilder.MapPost(route, actionFunc),
                MapTypeEnum.Put => _endpointRouteBuilder.MapPut(route, actionFunc),
                MapTypeEnum.Patch => _endpointRouteBuilder.MapPut(route, actionFunc),
                MapTypeEnum.Delete => _endpointRouteBuilder.MapDelete(route, actionFunc),
                _ => _endpointRouteBuilder.MapGet(route, actionFunc),
            };
            _ = routeHandlerBuilder
               .WithTags(_group)
               .WithSummary(summary)
               .WithOpenApi();
            return this;
        }
    }
}
